//
//  DetailViewController.m
//  FinApp
//
//  Created by Victor Leandro Fernandez Rodrigo on 12/11/11.
//  Copyright (c) 2011 FIB-Fàcultat d'informàtica de Barcelona. All rights reserved.
//

#import "DetailViewController.h"
#import "FinAppsImageView.h"
#import "AppDelegate.h"
#import "LocationManager.h"
#import "FavoritsController.h"

@interface DetailViewController()

- (void)buildDetail;
- (void)setBackBarButtonItemNewLocalizedText;
- (NSString *)createMessage;
- (void)displayComposerSheet;
- (void)launchMailAppOnDevice;

@end


@implementation DetailViewController

@synthesize navigationBar, priceLabel, cityLabel, addresLabel, moreInfoLabel;
@synthesize equipmentLabel, equipmentTitleLabel, notifyLabel, notifyButton, idFlat;
@synthesize descriptionLabel, descriptionTitleLabel, flatImage, flat, scrollView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //Set title text
    [navigationBar.topItem setTitle:NSLocalizedString(@"_detalle", @"")];
    
    [(AppDelegate*)[[UIApplication sharedApplication] delegate] showBigActivityWithText:NSLocalizedString(@"_carregantPisos", @"")];
    if(flat) {
        [self buildDetail];
        [[RestConsumer sharedInstance] getDetailOfProductWithID:[flat idFlat] withDelegate:self];
    } else {
        [[RestConsumer sharedInstance] getDetailOfProductWithID:idFlat withDelegate:self];
    }
    [self setBackBarButtonItemNewLocalizedText];
    
    //Add favorites button to navigation bar
    UIImage *favoriteImage;    
    if ([FavoritsController isFavourite:[flat idFlat]]) {
        favoriteImage = [UIImage imageNamed:@"detelle_star_.png"];
    }
    else favoriteImage = [UIImage imageNamed:@"detelle_star.png"];
    UIBarButtonItem *aBarButtonItem = [[UIBarButtonItem alloc] initWithImage:favoriteImage style:UIBarButtonItemStyleBordered target:self action:@selector(favoriteOnClick)];
    [navigationBar.topItem setRightBarButtonItem:aBarButtonItem]; 
    [aBarButtonItem release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [notifyButton release];
    [navigationBar release];
    [scrollView release];
    [priceLabel release];
    [cityLabel release];
    [addresLabel release];
    [moreInfoLabel release];
    [notifyLabel release];
    [equipmentLabel release];
    [equipmentTitleLabel release];
    [descriptionLabel release];
    [descriptionTitleLabel release];
    [flatImage release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) dealloc {
    [notifyButton release];
    [navigationBar release];
    [scrollView release];
    [priceLabel release];
    [cityLabel release];
    [addresLabel release];
    [moreInfoLabel release];
    [notifyLabel release];
    [equipmentLabel release];
    [equipmentTitleLabel release];
    [descriptionLabel release];
    [descriptionTitleLabel release];
    [flatImage release];
    [super dealloc];
}

#pragma mark - Private Methods

- (void)favoriteOnClick {
    //isFavourite?
    // yes-> imageNo
    // no->  imageYes / addToFavourites
    
    UIImage *favoriteImage;
    
    if ([FavoritsController isFavourite:[flat idFlat]]) {
        //Delete favourite
        favoriteImage = [UIImage imageNamed:@"detelle_star.png"];
        [FavoritsController deleteFavourite:[flat idFlat]];
        
        //Show Alert for WineRemoved
        UIAlertView *flatRemovedFromFavourites = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_flatRemoved", @"") message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_aceptar", @"") otherButtonTitles:nil];
        
        [flatRemovedFromFavourites show];
        [flatRemovedFromFavourites release];
    }
    else {
        //Add favourite
        favoriteImage = [UIImage imageNamed:@"detelle_star_.png"];
        NSDictionary *flatDict = [ListFlat dictionaryFromFlat:flat];
        [FavoritsController addFavouriteToListWithFlat:flatDict];
        
        //Show Alert for WineAdded
        UIAlertView *flatAddedToFavourites = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_flatAdded", @"") message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_aceptar", @"") otherButtonTitles:nil];
        
        [flatAddedToFavourites show];
        [flatAddedToFavourites release];
    }
    
    //Add startImage button to navigationBar
    UIBarButtonItem *aBarButtonItem = [[UIBarButtonItem alloc] initWithImage:favoriteImage style:UIBarButtonItemStyleBordered target:self action:@selector(favoriteOnClick)];
    [navigationBar.topItem setRightBarButtonItem:aBarButtonItem]; 
    [aBarButtonItem release];
}

- (void)buildDetail {
    [priceLabel setText:[NSString stringWithFormat:@"%.0f €",[flat price]]];
    [cityLabel setText:[flat city]];
    [addresLabel setText:[flat street]];
    [moreInfoLabel         setText:[NSString stringWithFormat:@"%@, %dm, %d%@",[flat flatType], [flat dimensions],[flat numRooms],NSLocalizedString(@"_habAcronim", @"")]];
    [notifyLabel setText:NSLocalizedString(@"_notifyMe", @"")];
    [equipmentTitleLabel setText:NSLocalizedString(@"_equipament", @"")];
    if ([flat isKindOfClass:[Flat class]]) {
        [equipmentLabel setText:[flat equipment]];
    }
    [descriptionTitleLabel  setText:NSLocalizedString(@"_description", @"")];
    if ([flat isKindOfClass:[Flat class]]) {
        [descriptionLabel setText:[flat description]];
    }
    [scrollView setContentSize:CGSizeMake(320, 250)];
    
    FinAppsImageView *remoteImage = [[FinAppsImageView alloc] initWithFrame: CGRectMake(0, 0, flatImage.frame.size.width, flatImage.frame.size.height)]; 
    [remoteImage setContentMode:UIViewContentModeScaleAspectFill];
    [remoteImage loadImageFromURL:[NSURL URLWithString:[flat imageURL]] loadingImage:[UIImage imageNamed:@"default_restaurant_detail.png"]];    
    [flatImage addSubview:remoteImage];
    [remoteImage release];
}

- (IBAction)routePressed:(id)sender {
    CLLocation *currentLocation = [[LocationManager sharedInstance] myLocation];
    
    
    NSString *locationString = [@"@" stringByAppendingFormat:@"%.3f,%.3f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude];
    NSString *targetLocationString = [@"@" stringByAppendingFormat:@"%.3f,%.3f",[flat latitude],[flat longitude]];
    NSString *theString = [NSString stringWithFormat:@"http://maps.google.com/maps?saddr=%@&daddr=%@", locationString, targetLocationString];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:theString]];
}

- (IBAction)notifyMePressed:(id)sender {
    
    if (notifyButton.tag == 0) {
        notifyButton.tag = 1;
        [notifyButton setImage:[UIImage imageNamed:@"detalle_check_.png"] forState:UIControlStateNormal];
    }
    else {
        notifyButton.tag = 0;
        [notifyButton setImage:[UIImage imageNamed:@"detalle_check.png"] forState:UIControlStateNormal];
    }
    
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    localNotif.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
    
	// Notification details
    localNotif.alertBody = [NSString stringWithFormat:@"%@ %@ %@",NSLocalizedString(@"_elpisdelcarrer", @""),[flat street],NSLocalizedString(@"_habaixat", @"")];
	// Set the action button
    localNotif.alertAction = @"View";
    
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    localNotif.applicationIconBadgeNumber = 0;
    
	// Specify custom data for the notification
    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:[flat idFlat]] forKey:@"idFlat"];
    localNotif.userInfo = infoDict;
    
	// Schedule the notification
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    [localNotif release];
    
}

- (IBAction)sendMailPressed:(id)sender {
    //Control if its possible to send an email
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (mailClass != nil)
    {
        // We must always check whether the current device is configured for sending emails
        if ([mailClass canSendMail])
        {
            [self displayComposerSheet];
        }
        else
        {
            [self launchMailAppOnDevice];
        }
    }
    else
    {
        [self launchMailAppOnDevice];
    }
}

- (void)setBackBarButtonItemNewLocalizedText {
    
    navigationBar.topItem.leftBarButtonItem = nil;
    
    //Set BackBarButton 
    UIButton *customBackButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 37)];
    [customBackButton setBackgroundImage:[UIImage imageNamed:@"comun_btn_back.png"] forState:UIControlStateNormal];
    [customBackButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UILabel *backLabel = [[UILabel alloc] initWithFrame:CGRectMake(2, 0, 78, 35)];
    [backLabel setText:NSLocalizedString(@"_atras", @"")];
    [backLabel setTextAlignment:UITextAlignmentCenter];
    [backLabel setTextColor:[UIColor whiteColor]];
    [backLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14]];
    [backLabel setBackgroundColor:[UIColor clearColor]];
    
    UIView *customBackButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 37)];
    [customBackButtonView addSubview:customBackButton];
    [customBackButtonView addSubview:backLabel];
    [customBackButton release];
    [backLabel release];
    
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customBackButtonView];
    [navigationBar.topItem setLeftBarButtonItem:backBarButtonItem];
    [customBackButtonView release];
    [backBarButtonItem release];
}

- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - DataFetchingHandler

-(void)dataFetchingDidFailWithTag:(NSString*)tag andError:(NSError*)error {
    [(AppDelegate*)[[UIApplication sharedApplication] delegate] removeBigActivity];
}

-(void)dataFetchingCompleteWithTag:(NSString*)tag data:(id)aData andStatus:(NSInteger)status{
    NSDictionary *response = (NSDictionary*)aData;
    if ([[response objectForKey:@"responseCode"] intValue] != 200) {
        [self dataFetchingDidFailWithTag:tag andError:nil];
        return;
    }
    if ([tag isEqualToString:kDETAILTAG]) {
        //Get Data
        [(AppDelegate*)[[UIApplication sharedApplication] delegate] removeBigActivity];
        [self setFlat:[Flat flatFromDictionary:[response objectForKey:@"inmoble"]]];
        [self buildDetail];
        
    }
}

#pragma mark - MFMailComposeViewControllerDelegate Methods

- (NSString *)createMessage {
    
    NSString *message = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"_shareMailMessage", @""),[flat description]];
    
    return message;
}

- (void)displayComposerSheet {
    
    MFMailComposeViewController *mailComposerViewController = [[MFMailComposeViewController alloc] init];
	mailComposerViewController.mailComposeDelegate = self;
    
    NSString *message = [self createMessage];
	
	// Fill out the email body text
	[mailComposerViewController setMessageBody:message isHTML:NO];
    [mailComposerViewController setSubject:@""];
	[self presentModalViewController:mailComposerViewController animated:YES];
    [mailComposerViewController release];
}

// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {	
	// Notifies users about errors associated with the interface
    NSString *message;
	switch (result)
	{
		case MFMailComposeResultCancelled:
			message = NSLocalizedString(@"_email_canceled",@"");
			break;
		case MFMailComposeResultSaved:
			message = NSLocalizedString(@"_email_saved",@"");
			break;
		case MFMailComposeResultSent:
			message = NSLocalizedString(@"_email_sent",@"");
			break;
		case MFMailComposeResultFailed:
			message = NSLocalizedString(@"_email_failed",@"");
			break;
		default:
			message = NSLocalizedString(@"_email_not_sent",@"");
			break;
	}
	[self dismissModalViewControllerAnimated:YES];
    
    //Show alertView with result
    UIAlertView *mailResultAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_emailTitle",@"")
                                                              message:message 
                                                             delegate:self 
                                                    cancelButtonTitle:NSLocalizedString(@"_ok",@"") 
                                                    otherButtonTitles:nil];
    [mailResultAlert show];
    [mailResultAlert release];
}

// Launches the Mail application on the device.
-(void)launchMailAppOnDevice
{
    NSString *message = [self createMessage];
    
	NSString *recipients = @"";
	NSString *subject = @"";
    NSString *body = [NSString stringWithFormat:@"&body=%@",message];
	
	NSString *email = [NSString stringWithFormat:@"%@%@", recipients, subject, body];
	email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}


@end
